import fs from '@ohos.file.fs'; //文件操作
import { hilog } from '@kit.PerformanceAnalysisKit';

const TAG: string = '[FileUtil]'
export class FileUtil {
  /**
   * 创建文件夹
   * @param filePath
   * @returns
   */
  mkdir(filePath: string): string {
    try {
      let dir = this.getDirname(filePath);
      if (!fileUtil.isExistSync(dir)) {
        fs.mkdirSync(dir);
      }
      return filePath;
    } catch (error) {
      hilog.error(1, TAG, `writeBytes2File-> ${filePath} ${error}`);
      return undefined;
    }
  }

  /**
   * 文件是否存在
   * @param filePath
   * @returns
   */
  isExist(filePath: string): Promise<boolean> {
    return fs.access(filePath);
  }

  isExistSync(filePath: string): boolean {
    return fs.accessSync(filePath);
  }

  getDirname(filePath: string): string {
    return filePath.replace(/\/[^/]+$/, "");
  }

  rename(oldPath: string, newPath: string) {
    if (fileUtil.isExistSync(newPath)) {
      fs.unlinkSync(newPath);
    }
    fs.renameSync(oldPath, newPath)
  }
}

let fileUtil = new FileUtil();
export default fileUtil;